package com.sensetime.jv.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.sensetime.jv.entity.RolesJv;
import com.sensetime.jv.entity.UserRolesJv;
import com.sensetime.jv.entity.UsersJv;
import com.sensetime.jv.mapper.RolesMapper;
import com.sensetime.jv.mapper.UserRolesMapper;
import com.sensetime.jv.mapper.UsersMapper;
import com.sensetime.jv.service.UserRoleService;
import com.sensetime.jv.util.AssertUtil;
import com.sensetime.jv.vo.request.UserRoleEditRequestVO;
import com.sensetime.jv.vo.request.UserRoleRequestVO;
import com.sensetime.jv.vo.response.UserRoleRespVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private UserRolesMapper userRolesMapper;

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private RolesMapper rolesMapper;

    @Override
    public void addUserRole(UserRoleRequestVO requestVO) {
        // 校验用户是否存在
        checkUserExists(requestVO.getUserId());
        checkRoleExists(requestVO.getRoleId());
        //检测是否该用户已经绑定了该角色
        checkUserRoleExists(requestVO.getUserId(), requestVO.getRoleId());
        UserRolesJv userRolesJv = new UserRolesJv();
        BeanUtils.copyProperties(requestVO, userRolesJv);
        userRolesMapper.insert(userRolesJv);
    }

    private void checkUserRoleExists(Integer userId, Integer roleId) {
        boolean exists = new LambdaQueryChainWrapper<>(userRolesMapper).eq(UserRolesJv::getRoleId, roleId).eq(UserRolesJv::getUserId, userId).exists();
        AssertUtil.isTrue(!exists, "该用户已经绑定了该角色");
    }

    @Override
    @Transactional
    public void deleteUserRole(Integer userId, Integer roleId) {
        // 校验用户是否存在
        checkUserExists(userId);

        // 这里简单假设根据用户 ID 和角色 ID 删除用户角色关联记录
        // 实际可能需要更复杂的逻辑，如处理关联表的级联删除
        boolean remove = new LambdaUpdateChainWrapper<>(userRolesMapper).eq(UserRolesJv::getUserId, userId).eq(UserRolesJv::getRoleId, roleId).remove();
        AssertUtil.isTrue(remove, "删除用户角色关联失败");
    }

    @Override
    @Transactional
    public void updateUserRole(UserRoleEditRequestVO requestVO) {
        // 校验用户是否存在
        checkUserExists(requestVO.getUserId());
        checkRoleExists(requestVO.getRoleId());
        // 检查要更新的用户角色关联数据是否存在
        boolean existsOld = new LambdaQueryChainWrapper<>(userRolesMapper).eq(UserRolesJv::getRoleId, requestVO.getRoleId()).eq(UserRolesJv::getUserId, requestVO.getUserId()).exists();
        boolean exists = new LambdaQueryChainWrapper<>(userRolesMapper).eq(UserRolesJv::getRoleId, requestVO.getOldRoleId()).eq(UserRolesJv::getUserId, requestVO.getUserId()).exists();
        AssertUtil.isTrue(existsOld, "要更新的用户角色关联数据不存在");
        AssertUtil.isTrue(exists, "用户角色已存在，请选择绑定其他角色");
        deleteUserRole(requestVO.getUserId(), requestVO.getRoleId());
        UserRolesJv userRolesJv = new UserRolesJv();
        BeanUtils.copyProperties(requestVO, userRolesJv);
        userRolesMapper.updateById(userRolesJv);
    }

    @Override
    public List<UserRoleRespVO> getUserRoles() {
        // 查询用户的角色关联
        List<UserRolesJv> userRolesJvs = userRolesMapper.selectList(null); // 这里需要根据实际情况添加查询条件

        // 使用Map收集用户ID和对应的roleIds
        Map<Integer, List<Integer>> userRoleIdsMap = new HashMap<>();

        for (UserRolesJv userRole : userRolesJvs) {
            Integer userId = userRole.getUserId();
            Integer roleId = userRole.getRoleId();

            // 如果用户不存在于Map中，初始化一个空列表
            userRoleIdsMap.computeIfAbsent(userId, k -> new ArrayList<>()).add(roleId);
        }

        // 收集所有角色ID
        Set<Integer> allRoleIds = new HashSet<>();
        for (List<Integer> roleIds : userRoleIdsMap.values()) {
            allRoleIds.addAll(roleIds);
        }

        // 一次性查询所有角色信息
        List<RolesJv> rolesList = rolesMapper.selectByIds(new ArrayList<>(allRoleIds));

        // 将角色信息映射到角色ID
        Map<Integer, RolesJv> roleMap = rolesList.stream()
                .collect(Collectors.toMap(RolesJv::getId, role -> role));

        // 构建最终的响应对象
        List<UserRoleRespVO> respVOs = new ArrayList<>();
        for (Map.Entry<Integer, List<Integer>> entry : userRoleIdsMap.entrySet()) {
            Integer userId = entry.getKey();
            List<Integer> roleIds = entry.getValue();

            // 查询用户信息
            UsersJv user = usersMapper.selectById(userId);
            if (user == null) {
                continue; // 如果用户不存在，跳过
            }

            // 构建UserRoleRespVO对象
            UserRoleRespVO respVO = new UserRoleRespVO();
            respVO.setUserId(userId);
            respVO.setUserName(user.getUsername());

            // 收集用户的角色列表
            List<RolesJv> userRoles = roleIds.stream()
                    .map(roleMap::get)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            respVO.setRoles(userRoles);
            respVOs.add(respVO);
        }

        return respVOs;
    }

    private void checkUserExists(Integer userId) {
        UsersJv user = usersMapper.selectById(userId);
        AssertUtil.notNull(user, "用户不存在");
    }

    private void checkRoleExists(Integer roleId) {
        RolesJv rolesJv = rolesMapper.selectById(roleId);
        AssertUtil.notNull(rolesJv, "角色不存在");
    }
}